package com.vess.ratingweb;

import java.io.InputStream;
import com.facebook.LoggingBehavior;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.Settings;
import com.facebook.model.GraphUser;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;

@SuppressLint("NewApi")
public class Login extends Activity {

	Button btnSubmit;

	Twitter twitter;
	RequestToken requestToken;
	private Session.StatusCallback statusCallback = new SessionStatusCallback();
	// Please put the values of consumerKy and consumerSecret of your app
	public final static String consumerKey = "rlo3UnxF7q1vddIDid8IKw"; // "your key here";
	public final static String consumerSecret = "Vya06KXbIwMmELM8V3ZbFS3xCvqu5dUsqqiaUnbcCY"; // "your secret key here";
	private final String CALLBACKURL = "callback://main"; // Callback URL that
															// tells the WebView
															// to load this
															// activity when it
															// finishes with
															// twitter.com. (see
															// manifest)
	private RadioGroup rgLoginButton;
	private String url;
	private CheckBox chbAgreement;
	private String mStrUsername;
	private String mStrTimeStamp, mStrLogo, mStrCoupon;
	private int mIntUserId;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);

		btnSubmit = (Button) findViewById(R.id.btnSubmit);
		rgLoginButton = (RadioGroup)findViewById(R.id.linInfo);
		chbAgreement = (CheckBox)findViewById(R.id.chbAgreement);
		
		mStrUsername = getIntent().getStringExtra("username");
		mStrTimeStamp = getIntent().getStringExtra("timestamp");
		mStrLogo = getIntent().getStringExtra("logo");
		mStrCoupon = getIntent().getStringExtra("coupon");
		mIntUserId = getIntent().getIntExtra("id", 0);
		
		/*String strText="";
		int sdk = android.os.Build.VERSION.SDK_INT;
        if(sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
            android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
            strText = clipboard.getText().toString(); 
        } else {
            android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); 
            android.content.ClipData.Item item = clipboard.getPrimaryClip().getItemAt(0);
            strText = item.getText().toString();
        }
        Toast.makeText(getApplicationContext(), strText, Toast.LENGTH_SHORT).show();*/
		
		new DownloadImageTask((ImageView) findViewById(R.id.imgLoginLogo))
		.execute("http://reputation.bonothemes.com/user/php/uploads/" + mStrLogo);
		
		rgLoginButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				switch (checkedId) {
				case R.id.btnLoginFB:
					url = "http://m.facebook.com/login.php";
					break;
				case R.id.btnLoginGoogle:
					url = "https://accounts.google.com/Login";
					break;
				case R.id.btnLoginTwitter:
					url = "https://twitter.com/login";
					break;
				case R.id.btnLoginWinlive:
					url = "https://login.live.com/?pcexp=false";
					break;
				case R.id.btnLoginYahoo:
					url = "http://mlogin.yahoo.com/";
					break;
				default:
					break;
				}
			}
		});
		
		btnSubmit.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (chbAgreement.isChecked()) {
					Intent intent = new Intent(Login.this, LoginForm.class);
					intent.putExtra("url", url);
					intent.putExtra("username", mStrUsername);
					intent.putExtra("timestamp", mStrTimeStamp);
					intent.putExtra("logo", mStrLogo);
					intent.putExtra("coupon", mStrCoupon);
					intent.putExtra("id", mIntUserId);
					startActivity(intent);
				} else {
					Toast.makeText(Login.this, "Please agree our Terms of Service", Toast.LENGTH_SHORT).show();
				}
				
			}
		});
		
		Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);

		Session session = Session.getActiveSession();
		Log.i("onCreate", Session.getActiveSession() + "");
		if (session == null) {
			if (savedInstanceState != null) {
				session = Session.restoreSession(this, null, statusCallback,
						savedInstanceState);
			}
			if (session == null) {
				session = new Session(this);
			}
			Session.setActiveSession(session);
			if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
				session.openForRead(new Session.OpenRequest(this)
						.setCallback(statusCallback));
			}
		}
		updateView();
	}

	private void onClickLogin() {
		Session session = Session.getActiveSession();
		Log.i("onClickLogin", " - session.isOpened() :" + session.isOpened());
		Log.i("onClickLogin", " - session.isClosed() :" + session.isClosed());
		if (!session.isOpened() && !session.isClosed()) {
			session.openForRead(new Session.OpenRequest(this)
					.setCallback(statusCallback));
			Log.i("onClickLogin if",
					" - session.isOpened() :" + session.isOpened());
			Log.i("onClickLogin if",
					" - session.isClosed() :" + session.isClosed());
		} else {
			Log.i("onClickLogin else",
					" - session.isOpened() :" + session.isOpened());
			Log.i("onClickLogin else",
					" - session.isClosed() :" + session.isClosed());
			Session.openActiveSession(this, true, statusCallback);
		}
	}

	private class SessionStatusCallback implements Session.StatusCallback {
		@Override
		public void call(Session session, SessionState state,
				Exception exception) {
			updateView();
		}
	}

	private void updateView() {
		Session session = Session.getActiveSession();
		Log.i("in updateView", "passed");
		Log.i("session.isOpened()", " - " + session.isOpened());
		Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {

			// callback after Graph API response with user object

			@Override
			public void onCompleted(GraphUser user, Response response) {
				if (user != null) {
					Toast.makeText(Login.this, user.getName(), Toast.LENGTH_LONG).show(); 
				}				
			}
		});
		if (session.isOpened()) {
			Intent intent = new Intent(Login.this, Directory.class);
			intent.putExtra("username",mStrUsername);
			intent.putExtra("timestamp", mStrTimeStamp);
			intent.putExtra("logo", mStrLogo);
			intent.putExtra("coupon", mStrCoupon);
			intent.putExtra("id", mIntUserId);
			startActivity(intent);
		} else {
			Log.i("session is closed", "passed");
			// textInstructionsOrLink.setText("session is closed");
			// buttonLoginLogout.setText(R.string.login);
/*			btnLoginFB.setOnClickListener(new OnClickListener() {
				public void onClick(View view) {
					onClickLogin();
				}
			});*/
		}
	}

	@Override
	public void onStart() {
		super.onStart();
		Session.getActiveSession().addCallback(statusCallback);
	}

	@Override
	public void onStop() {
		super.onStop();
		Session.getActiveSession().removeCallback(statusCallback);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Session.getActiveSession().onActivityResult(this, requestCode,
				resultCode, data);
		Intent intent = new Intent(Login.this, Directory.class);
		intent.putExtra("username",mStrUsername);
		intent.putExtra("timestamp", mStrTimeStamp);
		intent.putExtra("logo", mStrLogo);
		intent.putExtra("coupon", mStrCoupon);
		intent.putExtra("id", mIntUserId);
		startActivity(intent);
		Log.i("onActivityResult", " - resultCode :" + resultCode);
		Log.i("onActivityResult", " - requestCode :" + requestCode);
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		Session session = Session.getActiveSession();
		Session.saveSession(session, outState);
		Log.i("onClickLogin", " - session.isOpened() :" + session.isOpened());
		Log.i("onClickLogin", " - session.isClosed() :" + session.isClosed());
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		Uri uri = intent.getData();
		try {
			String verifier = uri.getQueryParameter("oauth_verifier");
			AccessToken accessToken = twitter.getOAuthAccessToken(requestToken,
					verifier);
			String token = accessToken.getToken(), secret = accessToken
					.getTokenSecret();
			// displayTimeLine(token, secret,accessToken); //after everything,
			// display the first tweet

		} catch (TwitterException ex) {
			Log.e("Main.onNewIntent", "" + ex.getMessage());
		}

	}

	void OAuthLogin() {
		try {
			twitter = new TwitterFactory().getInstance();
			twitter.setOAuthConsumer(consumerKey, consumerSecret);
			requestToken = twitter.getOAuthRequestToken(CALLBACKURL);
			Log.d("authUrl", requestToken.getAuthenticationURL());
			String authUrl = requestToken.getAuthenticationURL();

			this.startActivity(new Intent(Intent.ACTION_VIEW, Uri
					.parse(authUrl)));
		} catch (TwitterException ex) {
			Toast.makeText(this, ex.getMessage(), Toast.LENGTH_LONG).show();
			Log.e("in Main.OAuthLogin", ex.getMessage());
		}
	}
	
	private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
		ImageView bmImage;

		public DownloadImageTask(ImageView bmImage) {
			this.bmImage = bmImage;
		}

		protected Bitmap doInBackground(String... urls) {
			String urldisplay = urls[0];
			Bitmap mIcon11 = null;
			try {
				InputStream in = new java.net.URL(urldisplay).openStream();
				mIcon11 = BitmapFactory.decodeStream(in);
			} catch (Exception e) {
				Log.e("Error", e.getMessage());
				e.printStackTrace();
			}
			return mIcon11;
		}

		protected void onPostExecute(Bitmap result) {
			bmImage.setImageBitmap(result);
		}
	}
}
